package ext.tianma.part;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

import wt.enterprise.Master;
import wt.enterprise.RevisionControlled;
import wt.fc.Persistable;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.util.WTException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigException;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.struct.StructHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.erp.attributes.EnumerationUtil;
import ext.generic.erp.util.BOMStructureUtil;
import ext.tianma.bom.workflow.BOMBusinessUtil;
import ext.tianma.bom.workflow.WTPartToolUtil;
import ext.tianma.part.forms.TMTypeUtil;

public class PartDescriptionUtil{

	/**
	 * 生成并设置说明的描述
	 * 
	 * @param part
	 */
	public static void setPartDescription(WTPart part) {

		if (part == null) {
			return;
		}
		// 成品:产品分级-名称-TFT MODEL ID
		if (TMTypeUtil.isFinishedGood(part)) {
			setFinishedGoodDescription(part);
		}
		// 半成品
		else if (TMTypeUtil.isSemiFinishedGood(part)) {

			// C4:中文名称-偏光片AB规类型/面板亮雾面说明
			if (TMTypeUtil.isC4(part)) {
				setC4Description(part);
			}
			// CF:中文名称-图纸编号
			else if (TMTypeUtil.isCF(part)) {
				setCFDescription(part);
			}
			// 普通半成品:中文名称-主要规格-图纸编号/工艺文件编号-集成度
			else {
				setSemiFinishedGoodDescription(part);
			}
		}
		// 原材料:
		else if (TMTypeUtil.isRawMaterial(part)) {

			// 偏光片:产品分类-中文名称-成品型号-材料型号/图纸编号-主要规格
			if (TMTypeUtil.isPolarizer(part)) {
				setPolarizerDescription(part);
			}
			// 虚拟偏光片:中文名称-上/下偏光片料号
			else if (TMTypeUtil.isPhantomPolarizer(part)) {
				setPhantomPolarizerDescription(part);
			}
			// 普通原材料:产品分类-中文名称-材料型号/图纸编号-主要规格
			else {
				setRawMaterialDescription(part);
			}

		}
		// 二级物料不处理
		else if (TMTypeUtil.isTwoLevelMaterial(part)) {

		}
	}

	/**
	 * 普通原材料:产品分级-中文名称-材料型号/图纸编号-主要规格
	 * 
	 * @param part
	 */
	private static void setRawMaterialDescription(WTPart part) {

		try {
			// 产品分级
			String materialClassification = (String) IBAUtil.getIBAValue(part,
					"materialClassification");
			// 中文名称
			String partCName = (String) IBAUtil.getIBAValue(part, "partCName");
			// 材料型号/图纸编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");
			// 主要规格
			String partMainSpecification = (String) IBAUtil.getIBAValue(part,
					"partMainSpecification");
			
			//物料所属部门【工序】
			
			String departments = (String) IBAUtil.getIBAValue(part,
					"departments");
			
			String environCategory = getEnvironCategory(part);
			
			String partDesc = null;
			if(checkEffectiveSite(part)) {
				String[] descArray = { materialClassification, partCName,
					partDrawingNumber, partMainSpecification,environCategory,departments};
				
				partDesc = jointString(descArray);
			}
			else {
				String[] descArray = { materialClassification, partCName,
						partDrawingNumber, partMainSpecification,departments};
				
			    partDesc = jointString(descArray);
			}
			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 虚拟偏光片:中文名称-上/下偏光片料号
	 * 
	 * @author xuge_ning
	 * @param part
	 */
	private static void setPhantomPolarizerDescription(WTPart part) {

		try {
			// 中文名称
			String partCName = (String) IBAUtil.getIBAValue(part, "partCName");
			// 上/下偏光片料号
			String MtlNumofPOLTop = (String) IBAUtil.getIBAValue(part,
					"MtlNumofPOLTop");
			String MtlNumofPOLBtn = (String) IBAUtil.getIBAValue(part,
					"MtlNumofPOLBtn");
			String partDrawingNumber = "上偏：" + (MtlNumofPOLTop==null?"":MtlNumofPOLTop) + "，下偏："
					+ (MtlNumofPOLBtn==null?"":MtlNumofPOLBtn);
			
			String environCategory = getEnvironCategory(part);
			
			String partDesc = null;
			if(checkEffectiveSite(part)) {
				String[] descArray =  { partCName, partDrawingNumber, environCategory};
				
				partDesc = jointString(descArray);
			}else {
				String[] descArray = { partCName, partDrawingNumber };
				
				partDesc = jointString(descArray);
			}
			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	private static String getEnvironCategory(WTPart part) throws WTException, RemoteException {
		//环保类别
		String ibaValue =  (String) IBAUtil.getIBAValue(part,
				"partEnvProtectionCategory");
		String environCategory="";
		if( ibaValue != null && !ibaValue.isEmpty()){
			String environValue = EnumerationUtil.getEnumerationDisplayValue( "环保类别" , ibaValue);
			if(StringUtils.isNotBlank(environValue)) {
				environCategory = "("+ environValue +")";
			}
		}
		return environCategory;
	}

	/**
	 * 偏光片:产品分级-中文名称-材料型号/图纸编号-成品型号-主要规格
	 * 
	 * @param part
	 */
	private static void setPolarizerDescription(WTPart part) {

		try {
			// 产品分级
			String materialClassification = (String) IBAUtil.getIBAValue(part,
					"materialClassification");
			// 中文名称
			String partCName = (String) IBAUtil.getIBAValue(part, "partCName");
			// 成品型号
			String finishedGoodType = (String) IBAUtil.getIBAValue(part,
					"finishedGoodType");
			// 材料型号/图纸编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");
			// 主要规格
			String partMainSpecification = (String) IBAUtil.getIBAValue(part,
					"partMainSpecification");
			
			String environCategory = getEnvironCategory(part);
			
			String partDesc = null;
			if(checkEffectiveSite(part)) {
				String[] descArray = { materialClassification, partCName,
						partDrawingNumber, finishedGoodType, partMainSpecification,environCategory };
				
				partDesc = jointString(descArray);
			}else {
				String[] descArray = { materialClassification, partCName,
						partDrawingNumber, finishedGoodType, partMainSpecification };
				
				partDesc = jointString(descArray);
			}
			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);
			
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 普通半成品:中文名称-主要规格-图纸编号/工艺文件编号-集成度
	 * 目前需要修改为中文名称-线体-切割方式-加工方式及薄化前后厚度-图纸编号/工艺文件编号-集成度
	 * 
	 * @param part
	 */
	private static void setSemiFinishedGoodDescription(WTPart part) {

		try {
			// 中文名称
			String name = part.getName();
			// 主要规格
			// String partMainSpecification = (String)IBAUtil.getIBAValue(part,
			// "partMainSpecification");
			// 图纸编号/工艺文件编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");
			// 集成度
			String integration = (String) IBAUtil.getIBAValue(part,
					"Integration");
			integration = integration+"PANEL";
			// 线体
			String finishedGoodLineBody = (String) IBAUtil.getIBAValue(part,
					"finishedGoodLineBody");
			System.out.println("Debug   finishedGoodLineBody:"
					+ finishedGoodLineBody);
			// 切割方式
			String cuttingMode = (String) IBAUtil.getIBAValue(part,
					"cuttingMode");
			// 加工方式及薄化前后厚度
			String processingModeAndThickness = (String) IBAUtil.getIBAValue(
					part, "processingModeAndThickness");

			String[] descArray = { name, finishedGoodLineBody, cuttingMode,
					processingModeAndThickness, partDrawingNumber, integration };

			String partDesc = semiFinishedGoodJointString(descArray);

			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * CF:名称-图纸编号
	 * 
	 * @param part
	 */
	private static void setCFDescription(WTPart part) {

		try {
			// 名称
			String name = part.getName();
			// 图纸编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");

			String[] descArray = { name, partDrawingNumber };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * C4:名称-偏光片AB规类型/面板亮雾面说明
	 * 
	 * @param part
	 */
	private static void setC4Description(WTPart part) {

		try {
			// 名称
			String name = part.getName();
			// 偏光片AB规类型/面板亮雾面说明
			String polaroidType = (String) IBAUtil.getIBAValue(part,
					"polaroidType");

			String[] descArray = { name, polaroidType };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 成品:产品分级-名称-TFT MODEL ID
	 * 
	 * @param part
	 */
	private static void setFinishedGoodDescription(WTPart part) {

		try {
			// 名称
			String name = part.getName();
			// 产品分级
			String productClassification = (String) IBAUtil.getIBAValue(part,
					"productClassification");
			// TFT MODEL ID
			String TFTMODELID = (String) IBAUtil
					.getIBAValue(part, "TFTMODELID");

			String[] descArray = { productClassification, name, TFTMODELID };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "partDescription", partDesc);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 生成并设置“物料详细说明”的描述(成品，原材料，偏光片存在)
	 * 
	 * @param part
	 */
	public static void setPartDescriptionDetail(WTPart part) {

		if (part == null) {
			return;
		}
		// 成品:产品尺寸-名称(上海 成都 武汉 厦门使用)
		if (TMTypeUtil.isFinishedGood(part)) {
			setFinishedGoodDetail(part);
		}
		// 原材料
		else if (TMTypeUtil.isRawMaterial(part)) {
			// 偏光片:材料型号/图纸编号-主要规格（深圳用）
			if (TMTypeUtil.isPolarizer(part)) {
				setPolarizerDetail(part);
			}
			// 虚拟偏光片不处理
			else if (TMTypeUtil.isPhantomPolarizer(part)) {

			}
			// 普通原材料:材料型号/图纸编号-主要规格（深圳用）
			else {
				setRawMaterialDetail(part);
			}
		}

	}

	/**
	 * 普通原材料:材料型号/图纸编号-主要规格（深圳用）
	 * 
	 * @param part
	 */
	private static void setRawMaterialDetail(WTPart part) {

		try {
			// 材料型号/图纸编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");
			// 主要规格（深圳用）
			String partMainSpecification = (String) IBAUtil.getIBAValue(part,
					"partMainSpecification");

			String[] descArray = { partDrawingNumber, partMainSpecification };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "materialDetails", partDesc);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 偏光片:材料型号/图纸编号-主要规格（深圳用）
	 * 
	 * @param part
	 */
	private static void setPolarizerDetail(WTPart part) {

		try {
			// 材料型号/图纸编号
			String partDrawingNumber = (String) IBAUtil.getIBAValue(part,
					"partDrawingNumber");
			// 主要规格（深圳用）
			String partMainSpecification = (String) IBAUtil.getIBAValue(part,
					"partMainSpecification");

			String[] descArray = { partDrawingNumber, partMainSpecification };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "materialDetails", partDesc);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 成品:产品尺寸-名称(上海 成都 武汉 厦门使用)
	 * 
	 * @param part
	 */
	private static void setFinishedGoodDetail(WTPart part) {

		try {
			// 产品尺寸
			String finishedGoodSize = (String) IBAUtil.getIBAValue(part,
					"finishedGoodSize");
			// 名称(上海 成都 武汉 厦门使用)
			String name = part.getName();

			String[] descArray = { finishedGoodSize+"\"", name };

			String partDesc = jointString(descArray);

			IBAUtil.forceSetIBAValue(part, "materialDetails", partDesc);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	public static String jointString(String[] strArray) {
		String defaultConnectStr = "-";
		return jointString(strArray, defaultConnectStr);
	}

	public static String jointString(String[] strArray, String connectStr) {
		String result = "";

		if (strArray == null || strArray.length == 0) {
			return result;
		}

		if (connectStr == null) {
			connectStr = "";
		}

		for (int i = 0; i < strArray.length; i++) {
			if (strArray[i] != null) {
				strArray[i] = strArray[i].trim();

				// 修改原因:用户在某些地方不需要填写值得时候“NA”时，不往物料描述上添加。
				if (strArray[i].equals("NA")) {
					strArray[i] = "";
				}

				if (!strArray[i].equals("")) {
					if (result.length() == 0) {
						result = strArray[i];
					} else {
						result = result + connectStr + strArray[i];
					}
				}
			}
		}

		return result;
	}

	private static String semiFinishedGoodJointString(String[] strArray) {
		String defaultConnectStr = "-";
		return semiFinishedGoodJointString(strArray, defaultConnectStr);
	}

	private static String semiFinishedGoodJointString(String[] strArray,
			String connectStr) {
		String result = "";

		if (strArray == null || strArray.length == 0) {
			return result;
		}

		if (connectStr == null) {
			connectStr = "";
		}

		for (int i = 0; i < strArray.length; i++) {
			if (strArray[i] != null) {
				strArray[i] = strArray[i].trim();

				// 修改原因:用户在某些地方不需要填写值得时候“NA”时，不往物料描述上添加。
				if (strArray[i].equals("NA")) {
					strArray[i] = "";
				}

				if (!strArray[i].equals("其他")) {
					if (!strArray[i].equals("")) {
						if (result.length() == 0) {
							result = strArray[i];
						} else {
							result = result + connectStr + strArray[i];
						}
					}
				}
			}
		}

		return result;
	}

	// 成品下面的上下偏光片物料详细描述需要给到成品的PolTop、PolBottom by xuge_ning

	public static void setFinisheGoodChildDesc(WTArrayList parts) {
		if (parts == null) {
			return;
		}
		try {
			int size = parts.size();
			System.out.println("setFinisheGoodChildDesc method size : " + size);
			for (int i = 0; i < size; i++) {
				Persistable persistable = parts.getPersistable(i);
				if (persistable != null && persistable instanceof WTPart) {
					WTPart part = (WTPart) persistable;
					System.out
							.println("setFinisheGoodChildDesc method partNumber : "
									+ part.getNumber() + ":" + part.getName());
					if (TMTypeUtil.isFinishedGood(part)) {
						WTPart botPolarizer = null;
						WTPart topPolarizer = null;
						System.out
								.println("setFinisheGoodChildDesc method part : "
										+ part.getNumber());
						List<WTPart> list = getAllChildren(part);
						System.out
								.println("setFinisheGoodChildDesc method list size : "
										+ list.size());
						for (WTPart wtPart : list) {
							System.out.println("setFinisheGoodChildDesc method wtpart:" + wtPart.getNumber());
							if (TMTypeUtil.isBotPolarizer(wtPart)) {
								botPolarizer = wtPart;
								System.out
										.println("setFinisheGoodChildDesc method botPolarizer partNumber : "
												+ part.getNumber()
												+ ":"
												+ part.getName());
							} else if (TMTypeUtil.isTopPolarizer(wtPart)) {
								topPolarizer = wtPart;
								System.out
										.println("setFinisheGoodChildDesc method topPolarizer partNumber : "
												+ part.getNumber()
												+ ":"
												+ part.getName());
							}
							if (botPolarizer != null && topPolarizer != null) {
								break;
							}
						}
						if (botPolarizer != null) {
							String botDesc = (String) IBAUtil.getIBAValue(
									botPolarizer, "partDescription");
							IBAUtil.forceSetIBAValue(part, "PolTop", botDesc);
						}
						if (topPolarizer != null) {
							String topDesc = (String) IBAUtil.getIBAValue(
									topPolarizer, "partDescription");
							IBAUtil.forceSetIBAValue(part, "PolBottom", topDesc);
						}
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} finally {

		}
	}
	public static List<WTPart> getAllChildren(WTPart part) throws ConfigException, WTException {
//		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		
		List<WTPart> subPartList = new ArrayList<WTPart>() ;
		
		try{
			ConfigSpec latestconfigspec = getConfigSpec(part);
			
			QueryResult qr= StructHelper.service.navigateUsesToIteration(part,WTPartUsageLink.class,false,latestconfigspec);
			
			while(qr != null && qr.hasMoreElements()){
				//每一个element实际是一个persistable数组
				Persistable apersistable[] = ( Persistable[] ) qr.nextElement();  
				
				//数组中第一个对象是usagelink			
				//数组中第二个对象是子件
				//如果当前用户的权限正常，应该是个WTPart
				//反之返回的是WTPartMaster
				//一般是前一种情况居多，这样可以省掉查询子件最新版本的代码，这样代码的执行效率大大增加
				Object uses= apersistable[1];   
				
				WTPart subPart=null; 
				if( uses instanceof WTPart ){
//					System.out.println("uses instanceof WTPart") ;
					subPart=(WTPart)uses; 
				} else if( uses instanceof WTPartMaster ){
//					System.out.println("uses instanceof WTPartMaster") ;
					WTPartMaster master = (WTPartMaster) uses ;
					subPart = CoreUtil.getWTPartByMasterAndView(master, part.getViewName()) ;
				} else {
//					if( uses != null ){
//						System.out.println("Object uses Type is " + uses.getClass()) ;
//					}else{
//						System.out.println("Object uses == null !") ;
//					}
				}
				
				if( subPart != null ){
					subPartList.add(subPart) ;
					subPartList.addAll(getAllChildren(subPart));
				}
			}
		}finally{
//			SessionServerHelper.manager.setAccessEnforced(flag);
		}
		
		return subPartList;
	}

	/**
	 * 
	 * @param part
	 * @return
	 */
	private static ConfigSpec getConfigSpec(WTPart part) {
		ConfigSpec latestconfigspec = new LatestConfigSpec();
		
		String view = "";
		ViewReference viewRef =part.getView();
		if(viewRef != null){
			view = viewRef.getName();
		}
		try{
			if(view != null && view.length()>0){
				View viewObj= ViewHelper.service.getView(view);
				WTPartConfigSpec config = WTPartHelper.service.findWTPartConfigSpec();
				WTPartStandardConfigSpec standardConfig= config.getStandard();
				
				standardConfig.setView(viewObj);		
				latestconfigspec = standardConfig;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return latestconfigspec ;
	}
	
	/**
	 * 检查料号生效地是否为深圳C01 C02 CO4 C06 C08
	 * 
	 * 如果生效地为深圳，返回true
	 * 
	 * @param part
	 * 
	 * he_zhang2 2017-11-07
	 */
	public static boolean checkEffectiveSite(Object object)throws WTException {
		boolean flag = false;
		if (object == null) {
			return flag;
		}

		if ((object instanceof WTPart)) {
			WTPart part = (WTPart) object;
			if (TMTypeUtil.isATypeObject(part, ".RawMaterial")) {
				try {
					Vector effectiveSite = (Vector) IBAUtil.getIBAValue2(part,
							"partNumberEffectiveSite");
					List<String> siteList= new ArrayList();
					siteList.add("C01");
					siteList.add("C02");
					siteList.add("C04");
//					siteList.add("C06");
					siteList.add("C08");
					System.out.println("effectiveSite = " + effectiveSite);
					for(int i = 0;i< siteList.size();i++) {
						if(effectiveSite.contains(siteList.get(i))) {
							flag = true;
							return flag;
						}
					 }
				} catch (java.rmi.RemoteException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
}


